<template>
	<view class="container">
		<u-toast ref="uToast"></u-toast>
		<view class="order-card" v-if="orderData">
			<!-- 顶部装饰条 -->
			<view class="header-decorator"></view>

			<!-- 订单头部 -->
			<view class="order-header">
				<text class="order-title">场地预约订单</text>
				<view class="order-status" :class="statusClass">{{ orderStatusText }}</view>
			</view>

			<!-- 订单信息 -->
			<view class="info-group">
				<view class="info-title">
					<view class="title-decorator"></view>
					<text>订单信息</text>
				</view>

				<view class="order-detail">
					<text class="detail-label">订单编号</text>
					<text class="detail-value">{{ orderData.orderSn }}</text>
				</view>

				<view class="order-detail">
					<text class="detail-label">下单时间</text>
					<text class="detail-value">{{ orderData.orderTime }}</text>
				</view>
			</view>

			<!-- 分隔线 -->
			<view class="divider"></view>

			<!-- 预约详情 -->
			<view class="info-group">
				<view class="info-title">
					<view class="title-decorator"></view>
					<text>预约详情</text>
				</view>

				<view class="order-detail">
					<text class="detail-label">预约时间</text>
					<text class="detail-value">{{ formatTime() }}</text>
				</view>

				<view class="order-detail">
					<text class="detail-label">场馆信息</text>
					<text class="detail-value">{{ orderData.venueName }} - {{ orderData.partitionName }}
						{{ orderData.courtIndex + 1 }}号场地</text>
				</view>

				<view class="order-detail">
					<text class="detail-label">预订用户</text>
					<text class="detail-value">{{ orderData.userName }}</text>
				</view>
			</view>

			<!-- 分隔线 -->
			<view class="divider"></view>

			<!-- 价格区域 -->
			<view class="price-section">
				<text class="price-label">{{ orderData.orderStatus === 0 ? '应付金额' : '已付金额' }}</text><br>
				<text class="price">¥{{ orderData.payAmount.toFixed(2) }}</text>
			</view>

			<!-- 支付按钮 -->
			<button class="pay-btn" v-if="orderData && orderData.orderStatus === 0" @click="openPopup">立即支付</button>
			<!-- 退款按钮 -->
			<button class="refund-btn" v-if="orderData && orderData.orderStatus === 1"
				@click="handleRefund">申请退款</button>
		</view>
		<view v-else>
			<text>加载中...</text>
		</view>

		<!-- 支付弹窗 -->
		<u-popup :round="10" mode="center" :show="showPopup" @close="closePopup" @open="openPopup">
			<view class="pay-popup">
				<text class="popup-title">选择支付方式</text>
				<button class="pay-method wechat" @click="payWithWechat()">
					<u-icon name="weixin-fill" color="#fff" size="28"></u-icon>
					<text style="margin-left: 10rpx;">微信支付</text>
				</button>
				<button class="pay-method alipay" @click="payWithAlipay()">
					<u-icon name="zhifubao" color="#fff" size="28"></u-icon>
					<text style="margin-left: 10rpx;">支付宝</text>
				</button>
				<button class="cancel-btn" @click="closePopup">取消</button>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		getOrderRespDTOByOrderSn
	} from '@/api/book/order.js';
	import {
		pay,
		refund
	} from '@/api/book/pay.js';
	// import Constant from '@/constant/constant.js';
	export default {
		data() {
			return {
				orderData: null,
				orderSn: null,
				showPopup: false,
				isPayLoading: false
			};
		},
		onLoad(options) {
			this.orderSn = options.orderSn;
			this.fetchOrderData();
		},
		onShow() {
			if (this.orderSn) {
				this.retryCount = 0; // 初始化重试计数器
				this.maxRetries = 5; // 最大重试次数
				this.retryDelay = 1000; // 重试间隔(毫秒)
				this.fetchOrderDataWithRetry();
			}
		},
		computed: {
			orderStatusText() {
				if (!this.orderData) {
					return '订单数据为空';
				}
				switch (this.orderData.orderStatus) {
					case 0:
						return '待付款';
					case 1:
						return '已支付';
					case 4:
						return '已完成';
					case 2:
						return '已取消';
					case 3:
						return '已退款';
					default:
						return '未知状态';
				}
			},
			statusClass() {
				if (!this.orderData) return '';
				switch (this.orderData.orderStatus) {
					case 0: // 待付款
						return 'status-waiting';
					case 1: // 已支付
						return 'status-paid';
					case 4: // 已完成
						return 'status-completed';
					case 2: // 已取消
						return 'status-canceled';
					case 3: // 已退款
						return 'status-refunded';
					default:
						return '';
				}
			}
		},
		methods: {
			fetchOrderDataWithRetry() {
				this.fetchOrderData().then(() => {
					// 假设fetchOrderData返回一个Promise
					// 检查订单状态是否已更新(根据你的业务逻辑)
					if (this.orderData.orderStatus !== 1) {
						if (this.retryCount < this.maxRetries) {
							this.retryCount++;
							setTimeout(() => {
								this.fetchOrderDataWithRetry();
							}, this.retryDelay);
						} else {
							console.log('达到最大重试次数，订单状态仍未更新');
						}
					}
				}).catch(error => {
					console.error('获取订单数据失败:', error);
					if (this.retryCount < this.maxRetries) {
						this.retryCount++;
						setTimeout(() => {
							this.fetchOrderDataWithRetry();
						}, this.retryDelay);
					}
				});
			},
			async fetchOrderData() {
				try {
					const response = await getOrderRespDTOByOrderSn(this.orderSn);
					console.log('请求响应:', response);
					this.orderData = response.data;
				} catch (error) {
					console.error('获取订单数据失败:', error);
				}
			},
			// 格式化预约时间
			formatTime() {
				return `${this.orderData.periodDate} ${this.orderData.beginTime.substring(0, 5)}-${this.orderData.endTime.substring(0, 5)}`;
			},
			openPopup() {
				this.showPopup = true
			},
			// 关闭支付弹窗
			closePopup() {
				this.showPopup = false
			},
			async copyToClipboard(text) {
				try {
					// 优先使用现代 Clipboard API
					await navigator.clipboard.writeText(text);
					this.showPayLoading();
				} catch (err) {
					// console.error('使用Clipboard API失败，尝试备用方法:', err);
					// 备用方法
					const textarea = document.createElement('textarea');
					textarea.value = text;
					document.body.appendChild(textarea);
					textarea.select();
					document.execCommand('copy');
					document.body.removeChild(textarea);
					this.showPayLoading();
				}
			},

			showPayLoading() {
				this.$refs.uToast.show({
					type: 'loading',
					message: "支付宝账号已复制到剪贴板\n正在跳转支付，请稍等...", // 手动换行
					duration: 30000,
					icon: true,
					customStyle: {
						backgroundColor: 'rgba(0, 0, 0, 0.7)',
						color: '#fff',
						padding: '24rpx 40rpx',
						borderRadius: '16rpx',
						// 关键修改：使用 min-height 确保空间
						minHeight: '120rpx', // 增加最小高度
						alignItems: 'center'
					},
					iconStyle: {
						fontSize: '44rpx',
						color: '#fff',
						marginRight: '20rpx'
					},
					// 新增文字容器样式
					messageStyle: { // 如果 uView 支持这个参数
						lineHeight: '48rpx', // 明确单位
						paddingTop: '8rpx' // 手动微调
					}
				});
			},

			// 微信支付
			async payWithWechat() {
				this.closePopup();
				this.$refs.uToast.show({
					type: 'warning',
					message: "微信支付暂未开通"
				})
			},
			// 支付宝支付
			async payWithAlipay() {
				this.copyToClipboard('eseujj2902@sandbox.com');
				try {
					// 调用支付接口
					const currentPath = `/${getCurrentPages().pop().route}`;
					const returnUrl = `https://hellodam.website/#${currentPath}?orderSn=${this.orderSn}`;
					const resAlipay = await pay(
						this.orderSn,
						returnUrl
					);
					if (resAlipay.success) {
						// 显示更长时间（如1秒）让用户看清状态
						setTimeout(() => {
							window.location.href = resAlipay.data;
						}, 1000);
					} else {
						uni.showToast({
							title: '获取支付链接失败',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.showToast({
						title: '支付请求失败',
						icon: 'none'
					});
					console.error('支付失败:', error);
				} finally {
					uni.hideLoading();
					this.closePopup();
				}
			},
			// 处理退款
			handleRefund() {
				uni.showModal({
					title: '确认退款',
					content: '确定要申请退款吗？退款金额将原路返回您的支付账户',
					success: (res) => {
						if (res.confirm) {
							this.requestRefund();
						}
					}
				});
			},
			// 请求退款
			async requestRefund() {
				uni.showLoading({
					title: '正在处理退款...'
				});
				try {
					// 这里调用退款API
					const response = await refund(this.orderSn);
					if (response.success) {
						uni.showToast({
							title: '退款申请已提交',
							icon: 'success'
						});
						this.fetchOrderData(); // 刷新订单状态
					} else {
						uni.showToast({
							title: response.message || '退款申请失败',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.showToast({
						title: '退款请求失败',
						icon: 'none'
					});
					console.error('退款失败:', error);
				} finally {
					uni.hideLoading();
				}
			}
		}
	};
</script>

<style lang="scss">
	$primary-color: #4361ee;
	$secondary-color: #3f37c9;
	$accent-color: #4cc9f0;
	$success-color: #4caf50;
	$warning-color: #ff9800;
	$danger-color: #f44336;
	$light-color: #f8f9fa;
	$dark-color: #212529;
	$text-color: #333;
	$text-light: #666;
	$border-radius: 12px;
	$box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);

	.container {
		padding: 20rpx;
		background-color: #f5f7fa;
		min-height: 100vh;
	}

	.order-card {
		background-color: #fff;
		border-radius: $border-radius;
		box-shadow: $box-shadow;
		padding: 30rpx;
		position: relative;
		overflow: hidden;
		margin-bottom: 20rpx;
	}

	.header-decorator {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 8rpx;
		background: linear-gradient(90deg, $primary-color, $accent-color);
	}

	.order-header {
		text-align: center;
		margin-bottom: 40rpx;
		padding-bottom: 30rpx;
		border-bottom: 1rpx solid rgba(0, 0, 0, 0.05);

		.order-title {
			font-size: 36rpx;
			font-weight: 600;
			color: $dark-color;
			display: block;
			margin-bottom: 16rpx;
		}
	}

	.order-status {
		display: inline-block;
		padding: 10rpx 30rpx;
		color: white;
		border-radius: 40rpx;
		font-size: 26rpx;
		font-weight: 500;

		/* 不同状态的颜色 */
		&.status-waiting {
			background-color: $warning-color; // 待付款 - 橙色
		}

		&.status-paid {
			background-color: $success-color; // 已支付 - 绿色
		}

		&.status-completed {
			background-color: $primary-color; // 已完成 - 蓝色
		}

		&.status-canceled {
			background-color: $text-light; // 已取消 - 灰色
		}

		&.status-refunded {
			background-color: $danger-color; // 已退款 - 红色
		}
	}

	.info-group {
		margin-bottom: 40rpx;

		.info-title {
			font-size: 32rpx;
			font-weight: 600;
			color: $dark-color;
			margin-bottom: 30rpx;
			display: flex;
			align-items: center;

			.title-decorator {
				width: 6rpx;
				height: 32rpx;
				background-color: $primary-color;
				border-radius: 4rpx;
				margin-right: 16rpx;
			}
		}
	}

	.order-detail {
		margin-bottom: 30rpx;
		padding: 0 16rpx;
		display: flex;
		flex-direction: column;

		.detail-label {
			font-size: 28rpx;
			color: $text-light;
			margin-bottom: 12rpx;
			display: flex;
			align-items: center;

			&::before {
				content: '';
				display: inline-block;
				width: 8rpx;
				height: 8rpx;
				border-radius: 50%;
				background-color: $primary-color;
				margin-right: 16rpx;
			}
		}

		.detail-value {
			font-size: 32rpx;
			color: $text-color;
			font-weight: 500;
			margin-left: 24rpx;
		}
	}

	.price-section {
		text-align: center;
		margin: 50rpx 0;
		padding: 30rpx;
		background-color: rgba(67, 97, 238, 0.05);
		border-radius: $border-radius;

		.price-label {
			font-size: 28rpx;
			line-height: 60rpx;
			color: $text-light;
			margin-bottom: 18px;
		}

		.price {
			font-size: 64rpx;
			color: $primary-color;
			font-weight: 600;
		}
	}

	.pay-btn {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		background: linear-gradient(135deg, $primary-color, $secondary-color);
		color: white;
		border-radius: $border-radius;
		font-size: 34rpx;
		font-weight: 500;
		margin-top: 20rpx;
		box-shadow: 0 8rpx 24rpx rgba(67, 97, 238, 0.3);
		border: none;

		&::after {
			border: none;
		}

		&:active {
			opacity: 0.9;
			transform: translateY(2rpx);
		}
	}

	.refund-btn {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		background: linear-gradient(135deg, $danger-color, darken($danger-color, 10%));
		color: white;
		border-radius: $border-radius;
		font-size: 34rpx;
		font-weight: 500;
		margin-top: 20rpx;
		box-shadow: 0 8rpx 24rpx rgba(244, 67, 54, 0.3);
		border: none;

		&::after {
			border: none;
		}

		&:active {
			opacity: 0.9;
			transform: translateY(2rpx);
		}
	}

	.divider {
		height: 2rpx;
		background-color: rgba(0, 0, 0, 0.05);
		margin: 40rpx 0;
		position: relative;

		&::after {
			content: '···';
			position: absolute;
			left: 50%;
			top: 50%;
			transform: translate(-50%, -50%);
			background-color: white;
			padding: 0 24rpx;
			color: $text-light;
			font-size: 36rpx;
			letter-spacing: 8rpx;
		}
	}

	.pay-popup {
		background-color: #fff;
		border-radius: $border-radius;
		padding: 40rpx;
		width: 600rpx;

		.popup-title {
			font-size: 36rpx;
			font-weight: 600;
			color: $dark-color;
			display: block;
			text-align: center;
			margin-bottom: 40rpx;
		}
	}

	.pay-method {
		width: 100%;
		height: 100rpx;
		line-height: 100rpx;
		border-radius: $border-radius;
		font-size: 32rpx;
		font-weight: 500;
		margin-bottom: 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border: none;

		&::after {
			border: none;
		}

		.pay-icon {
			width: 50rpx;
			height: 50rpx;
			margin-right: 20rpx;
		}

		&.wechat {
			background-color: #07C160;
			color: white;
		}

		&.alipay {
			background-color: #1DA1F2;
			color: white;
		}
	}

	.cancel-btn {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		color: $text-light;
		font-size: 30rpx;
		background: none;
		border: none;
		margin-top: 20rpx;

		&::after {
			border: none;
		}
	}
</style>
